<?php

namespace App\Services\Pay;

use App\Actions\PayAction;
use App\Dao\OrderDao;
use App\Dao\UserDao;
use App\Exception\MessageException;
use App\Job\AutoAdReturnQueueJob;
use App\Model\ChannelSpread;
use App\Model\ConfigPayPlatform;
use App\Model\Order;
use App\Model\RechargeRestTotal;
use App\Model\User;
use App\Model\UserSuperVip;
use App\Model\UserVip;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use Hyperf\DbConnection\Db;
use function Hyperf\Translation\trans;

class PayCallbackCommon
{

    /**
     * Note - 支付回调公共方法
     * DateTime 2024/8/23 18:43
     * User Admin
     * @param $order_id
     * @param $trade_id
     */
    public function do($order_id, $trade_id)
    {
        if (!$order_id || !$trade_id) {
            throw new MessageException("订单信息错误！");
        }
        Db::beginTransaction();
        $orderInfo = OrderDao::getInstance()->findOrderByOrderId($order_id);
        $uid = $orderInfo['uid'];
        LoggerUtil::write("pay_callback_order", $orderInfo);
        $userInfo = UserDao::getInstance()->findUserInfoCache($orderInfo['uid']);
        if ($orderInfo['notify_status'] == 0 && $orderInfo['id'] > 0) {
            $data['pay_status'] = 1;//修改为成功状态
            $data['notify_status'] = 1;
            $data['trade_id'] = $trade_id;
            $rs = Order::query()->where('order_id', $order_id)->update($data);
            // 支付成功记录商户号收款数据
            ConfigPayPlatform::query()->where('id', $orderInfo['pay_platform_id'])->increment('collect_amount', $orderInfo['price']);
            if ($rs) {
                try {
                    MemcacheClient::getInstance()->delete("userInfo_" . $orderInfo['uid']);
                    $payAction = new PayAction();
                    $orderInfo = array_merge($orderInfo, $data);
                    //判断男用户是否开启了充值限制
                    if ($userInfo['sex'] == 1) {
                        // $rechargeRestTotalInfo = $rechargeRestTotalModel->find('id,uid,real_all_money', 'recharge_type = ? and auth_type=? and uid=?', [1, 1, $userInfo["id"]]);
                        $rechargeRestTotalInfo = RechargeRestTotal::query()->where('id', $userInfo["id"])->where('recharge_type', 1)->where('auth_type', 1)->select(['id', 'uid', 'real_all_money'])->exists();
                        $need_time = time();
                        if ($rechargeRestTotalInfo) {
                            // $rechargeRestTotalModel->updateByWhereSet("real_all_money=real_all_money+{$orderInfo['price']},update_time={$need_time}", "uid={$userInfo['id']} and auth_type=1 and recharge_type=1");
                            RechargeRestTotal::query()->where('uid', $userInfo['id'])->where('recharge_type', 1)
                                ->where('auth_type', 1)->where('recharge_type', 1)
                                ->update([
                                    'real_all_money' => Db::raw('real_all_money+' . $orderInfo['price']),
                                    'update_time' => $need_time
                                ]);
                        } else {
                            $insertAuditData = [
                                'uid' => $userInfo['id'],
                                'recharge_type' => 1,
                                'auth_type' => 1,
                                'real_all_money' => $orderInfo['price'],
                                'create_time' => $need_time,
                                'update_time' => $need_time
                            ];
                            // $rechargeRestTotalModel->insert($insertAuditData, "tb_recharge_rest_total");
                            RechargeRestTotal::query()->insert($insertAuditData);
                        }
                    }


                    if ($orderInfo['consume_type'] >= 50 && $orderInfo['consume_type'] < 70) {
                        //consume_type大于50为购买VIP
                        if ($orderInfo['consume_type'] >= 60) {
                            //SVIP
                            $sub_type = 8;
                            // $userSuperVip = new UserSuperVipModel();
                            $exists = UserSuperVip::query()->where('uid', $userInfo['id'])->exists();
                            if (!$exists) {
                                $data_1['content'] = trans('message.恭喜您成为SVIP');
                                $data_1['content_type'] = 3;
                                FunUtil::socket_client('assistant_uid', $userInfo['id'], '', $data_1);
                            }
                        } else {
                            //VIP
                            $sub_type = 2;
                            // $userVip = new UserVipModel();
                            // if (empty($userVip->find('id', 'uid =?', [$userInfo['id']]))) {
                            $exists = UserVip::query()->where('uid', $userInfo['id'])->exists();
                            if (!$exists)
                                $data_1['content'] = trans('message.恭喜您成为VIP');
                            $data_1['content_type'] = 3;
                            FunUtil::socket_client('assistant_uid', $userInfo['id'], '', $data_1);
                        }
                        $payAction->updateUserVipInfo($orderInfo);
                        // $userModel->updateByWhere(array("isNewUser" => 0, "get_free_video" => 0, "already_buy_gold" => 1, "paying_user" => 1), "id = '$uid'");
                        User::query()->where('id', $userInfo['id'])->update(["isNewUser" => 0, "get_free_video" => 0, "already_buy_gold" => 1, "paying_user" => 1]);
                        // $orderModel->commit();
                        Db::commit();
                    } elseif ($orderInfo['consume_type'] < 50) {
                        if (in_array($orderInfo['consume_type'], [0, 1])) {
                            // 购买微信、视频等
                            // $weixinRecordModel = new WeixinRecordModel();
                            // $weixinRecordModel->insert([
                            //     'uid' => $uid,
                            //     'anchor_id' => $orderInfo["order_robot_id"],
                            //     'extend' => $orderInfo['goods_id'],
                            //     'type' => $orderInfo['consume_type'],
                            //     'ctime' => time()
                            // ]);
                            //
                            // /** 购买微信粉丝圈发送消息 向男用户发送通知消息*/
                            // $rate = 0.4;
                            // $profit = bcmul($orderInfo['price'] * 10, $rate, 2);
                            // // 增加冻结积分
                            // (new PayCallModel())->addAnchorAccountFreeze($orderInfo["order_robot_id"], $profit);
                            // // 增加冻结记录
                            // (new UserAssetLockModel())->write($orderInfo["order_robot_id"], $profit, 1, $uid, '用户购买微信粉丝圈');
                            //
                            // /** 购买微信粉丝圈发送消息 */
                            // $nickname = $userModel->getValue($orderInfo['order_robot_id'], 'nickname');
                            // $data_1['content'] = "尊敬的用户您好，您已解锁 {$nickname} 的微信粉丝圈（微信号）如果对方没有及时添加您或者拒绝您，你可以联系客服申请退款；";
                            // $data_1['content_type'] = 3;
                            // Fun::socket_client('assistant_uid', $userInfo['id'], '', $data_1);
                            //
                            //
                            // /** 向女用户发送通知消息 */
                            // $data_2['content'] = "您的粉丝圈已被 {$userInfo['nickname']} 用户解锁，请及时通过该用户的好友申请，联系在线客服报备！";
                            // $data_2['content_type'] = 3;
                            // Fun::socket_client('assistant_uid', $orderInfo["order_robot_id"], '', $data_2);
                            //
                            // /** 男用户向女用户发送消息 */
                            // (new WyyClient())->putSendMsgQueue($uid, $orderInfo["order_robot_id"], '我解锁你的粉丝圈啦~快去微信通过我的好友申请吧~', 1, 4);
                        } else {
                            $rsPayAction = $payAction->userBuyGold($orderInfo);
                            // $userModel->updateByWhere(array("isNewUser" => 0, "get_free_video" => 0, "already_buy_gold" => 1, "paying_user" => 1), "id = '$uid'");
                            User::query()->where('id', $userInfo['id'])->update(["isNewUser" => 0, "get_free_video" => 0, "already_buy_gold" => 1, "paying_user" => 1]);
                            $isFirstRecharge = $payAction->checkFirstRecharge($orderInfo);
                        }
                        // $orderModel->commit();
                        Db::commit();
                    } else {
                        Db::rollBack();
                        throw new MessageException('未知的订单类型');
                    }
                } catch (\Throwable $e) {
                    Db::rollBack();
                    LoggerUtil::write("pay_callback_order", $e->getMessage());
                    throw new MessageException('订单回调处理失败');
                }


                // 更新用户总充值金额
                UserDao::getInstance()->updateUserRecharge($uid, $orderInfo['price']);
                // 更新用户充值限制数据
                // $userModel->execute("update tb_user_recharge_limit set recharge_count = recharge_count + {$orderInfo['price']} where uid=$uid and status=1");
                // 付费数据回传队列
                $registerTime = $userInfo['register_time'];
                // 24+2 付费回传
                $channel = $userInfo['channel'];
                $stdTime = strtotime(date("Y-m-d", $registerTime)) + (in_array($channel, ['huanyu68', 'huanyu74', 'huanyu80']) ? 86400 * 6 : 86400);
                if (time() <= $stdTime) {
                    try {
                        if (!in_array($channel, ['xy_oppo', 'xy_vivo']) || (!empty($isFirstRecharge) && empty($userInfo['inviteUid']))) {
                            // $sql = "SELECT is_zero FROM tb_channel_spread WHERE channel='$channel' AND spread_status=1";
                            // $is_zero = $userModel->findOneField($sql, 'is_zero', 0);
                            $is_zero = ChannelSpread::query()->where('channel', $channel)->where('spread_status', 1)->value('is_zero');
                            $price = intval($orderInfo['price'] * 100);
                            $properties = ($is_zero == 0) ? $price : 0;
                            $ip = $userInfo['last_login_ip'] ?? $userInfo['register_ip'];
                            $ext2 = json_decode($userInfo['ext2'], true);
                            $queueData = [
                                'uid' => $uid,
                                'imei' => $userInfo['imei'],
                                'oaid' => $userInfo['oaid'],
                                'from' => $userInfo['from'],
                                'event_type' => 'active_pay',
                                'channel' => $channel,
                                'price' => $price,
                                'properties' => $properties,
                                'ip' => $ip,
                                'order_id' => $orderInfo['id'],
                                'model' => $ext2['phone_brand'],
                                'ctime' => time(),
                            ];
                            // (new RedisConn())->getConn()->lPush("queue:auto_ad_return_queue", json_encode($queueData));
                            pushQueueMessage(AutoAdReturnQueueJob::class, $queueData);
                            LoggerUtil::write("auto_ad", $queueData, 'push');
                        } else {
                            LoggerUtil::write('pay_shop', $orderInfo);
                        }
                    } catch (\Throwable $e) {
                        LoggerUtil::write('pay_error', [$e->getFile(), $e->getCode(), $e->getMessage()]);
                    }
                }
                switch ($userInfo['channel']) {
                    case 'ybjyop':
                        UserDao::getInstance()->oppoAdDataReturn($userInfo['imei'], $userInfo['oaid'], $userInfo['package'], $orderInfo['id']);
                        break;
                }

            } else {
                // $orderModel->rollBack();
                Db::rollBack();
            }
            MemcacheClient::getInstance()->delete("get_new_user_list_data");
            MemcacheClient::getInstance()->delete("userInfo_" . $orderInfo['uid']);
            FunUtil::socket_client('pay_success', $userInfo['id'], $userInfo['session_id'], $orderInfo['consume_type']);
        } else {
            throw new MessageException('订单已被处理');
        }
    }


}